package pers.zw.web.controller;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import pers.zw.domain.User;
import pers.zw.exception.UserExistException;
import pers.zw.service.IUserService;
import pers.zw.service.impl.UserServiceImpl;
import pers.zw.util.WebUtils;
import pers.zw.web.formbean.RegisterFormBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 处理用户注册表单
 */
@WebServlet(name = "RegisterServlet", urlPatterns = "/Servlet/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RegisterFormBean formBean = WebUtils.requestToBean(request, RegisterFormBean.class);

        if (!formBean.validate()) {
            request.setAttribute("formBean", formBean);
            request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);
            return;
        }

        User user = new User();
        try {
            // 注册字符串到日期的转换器
            ConvertUtils.register(new DateLocaleConverter(), Date.class);
            BeanUtils.copyProperties(user, formBean);//把表单的数据填充到javabean中
            user.setId(WebUtils.makeId());//设置用户的Id属性
            IUserService service = new UserServiceImpl();
            //调用service层提供的注册用户服务实现用户注册
            service.registerUser(user);
            String message = String.format(
                    "注册成功！！3秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='3;url=%s'/>",
                    request.getContextPath()+"/Servlet/LoginUIServlet");
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request,response);

        } catch (UserExistException e) {
            formBean.getErrors().put("userName", "注册用户已存在！！");
            request.setAttribute("formBean", formBean);
            request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace(); // 在后台记录异常
            request.setAttribute("message", "对不起，注册失败！！");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }

    }
}
